﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using Agro.Models;
using System.Web.Security;
using SN.Data;
using System.Data;
using SN.Core;
using System.Web.Script.Serialization;

namespace Agro.Library {

    public class BaseController : Controller {

        protected override void OnActionExecuting(ActionExecutingContext filterContext) {
            //验证是否session是否超时 超时重新登录
            if (CurrUser == null) {
                filterContext.Result = new RedirectResult("~/Login/ReLogin");
            }
            base.OnActionExecuting(filterContext);
        }

        /// <summary>
        /// 当前用名
        /// </summary>
        /// 
        public CurrentUser CurrUser {
            get {
                return new CurrentUser();
            }
        }

        /// <summary>
        /// 获取模型验证的错误信息
        /// </summary>
        public IList<string> ModelErrors {
            get {
                List<string> errList = new List<string>();
                if (!ModelState.IsValid) {
                    errList = ModelState.Keys.SelectMany(m => ModelState[m].Errors).Select(m => m.ErrorMessage).ToList();
                }
                return errList;
            }
        }

        #region SNJsonResult...
        /// <summary>
        /// 
        /// </summary>
        /// <param name="data">返回数据</param>
        /// <param name="errorMessage">错误消息，无错时返回空字符串</param>
        /// <returns></returns>
        protected JsonResult SNJson(object data, string errorMessage) {
            return SNJson(data, errorMessage, JsonRequestBehavior.DenyGet);
        }

        protected JsonResult SNJson(string errorMessage) {
            return SNJson(null, errorMessage, JsonRequestBehavior.AllowGet);
        }

        protected JsonResult SNJson(IList<string> errorMessages) {
            var obj = new { Data = (object)null, ErrorMessage = errorMessages, Success = errorMessages.Count == 0 };
            return Json(obj);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="data">返回数据</param>
        /// <param name="errorMessage">错误消息，无错时返回空字符串</param>
        /// <param name="behavior"></param>
        /// <returns></returns>
        protected JsonResult SNJson(object data, string errorMessage, JsonRequestBehavior behavior) {
            SNJsonResult jsonResult = new SNJsonResult { ErrorMessage = errorMessage, Data = data, JsonRequestBehavior = behavior };
            return jsonResult;
        }

        #endregion

        #region JqGridResult...
        /// <summary>
        /// 创建一个输出到前台给JqGrid使用的数据源
        /// </summary>
        /// <param name="dt"></param>
        /// <param name="userData"></param>
        /// <param name="query"></param>
        /// <returns></returns>
        protected ActionResult JqGrid(DataTable dataTable, object userData, QueryBase query) {
            string _colModel = this.Request.Form["colModel"];
            if (!string.IsNullOrEmpty(_colModel)) {//发现列配置信息，认为是导出请求
                return JqGridExportExcel(dataTable);
            }
            JqGridResult result = new JqGridResult(query.page, query.rows, query.records, userData, dataTable);
            return result;
        }
        /// <summary>
        /// 创建一个输出到前台给JqGrid使用的数据源
        /// </summary>
        /// <param name="dataTable"></param>
        /// <param name="query"></param>
        /// <returns></returns>
        protected ActionResult JqGrid(DataTable dataTable, QueryBase query) {
            return JqGrid(dataTable, null, query);
        }
        /// <summary>
        /// 创建一个输出到前台给JqGrid使用的数据源
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="dataList"></param>
        /// <param name="query"></param>
        /// <returns></returns>
        protected ActionResult JqGrid<T>(IList<T> dataList, QueryBase query)
            where T : class {
            string _colModel = this.Request.Form["colModel"];
            if (!string.IsNullOrEmpty(_colModel)) {//发现列配置信息，认为是导出请求
                return JqGridExportExcel<T>(dataList);
            }
            JqGridResult<T> result = new JqGridResult<T>(query.page, query.rows, query.records, dataList);
            return result;
        }
        /// <summary>
        /// 创建一个输出到前台给JqGrid使用的数据源
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="dataList"></param>
        /// <param name="userData"></param>
        /// <param name="query"></param>
        /// <returns></returns>
        protected ActionResult JqGrid<T>(IList<T> dataList, object userData, QueryBase query)
            where T : class {
            JqGridResult<T> result = new JqGridResult<T>(query.page, query.rows, query.records, userData, dataList);
            return result;
        }
        /// <summary>
        /// 返回一个空的JqGrid数据
        /// </summary>
        /// <returns></returns>
        protected JqGridResult JqGrid() {
            JqGridResult result = new JqGridResult(1, 1, 0, null, new DataTable());
            return result;
        }
        #endregion

        #region OnException...
        //处理未捕获的异常
        protected override void OnException(ExceptionContext filterContext) {
            bool handled = true;
            filterContext.Controller.ViewData["ErrorMessage"] = filterContext.Exception.Message;
            if (filterContext.HttpContext.Request.IsAjaxRequest()) {
                if (!ModelState.IsValid) {
                    filterContext.Result = SNJson(ModelErrors);
                }
                else {
                    //暂时以此判定本次是Jqgrid发起的请求
                    //由于Jqgrid自带异常处理，所以请求异常时不再标识异常已处理。
                    if (filterContext.Exception.StackTrace.Contains("GetList") &&
                        filterContext.Exception.StackTrace.Contains("QueryBase")) {
                        handled = false;
                    }
                    else
                        filterContext.Result = SNJson(filterContext.Exception.Message);
                }
            }
            else {
                filterContext.Result = new ViewResult() {
                    ViewName = "Exception",
                    ViewData = filterContext.Controller.ViewData,
                };
            }
            filterContext.ExceptionHandled = handled;
            if (handled)
                filterContext.HttpContext.Response.TrySkipIisCustomErrors = true;
            base.OnException(filterContext);
        }
        #endregion

        #region ExcelResult...

        public ActionResult Excel(System.IO.MemoryStream stream, string fileName) {
            StreamExcelResult excelResult = new StreamExcelResult(stream, fileName);
            return excelResult;
        }
        #endregion



        /// <summary>
        /// JqGrid导出Excel
        /// </summary>
        /// <param name="_dataTable"></param>
        /// <returns></returns>
        public ActionResult JqGridExportExcel(DataTable _dataTable) {
            return new JqGridExportExcelResult(_dataTable);
        }
        /// <summary>
        /// JqGrid导出Excel
        /// Ajax方式 如果指定文件名会存在重名隐患
        /// </summary>
        /// <param name="_dataTable"></param>
        /// <param name="fileName"></param>
        /// <returns></returns>
        public ActionResult JqGridExportExcel(DataTable _dataTable, string fileName) {
            return new JqGridExportExcelResult(_dataTable, fileName);
        }

        public ActionResult JqGridExportExcel<T>(IList<T> dataList)
            where T : class {
            return JqGridExportExcel<T>(dataList, null);
        }

        public ActionResult JqGridExportExcel<T>(IList<T> dataList, string fileName)
            where T : class {
            return new JqGridExportExcelResult<T>(dataList, fileName);
        }
    }
}
